package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Transactional
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithChildrens() {
        List<CategoryEntity> all = baseMapper.selectList(null);
        List<CategoryEntity> res = all.stream().filter(category -> category.getParentCid() == 0)
                .map(category -> {
                    category.setChildren(getChildrens(category, all));
                    return category;
                }).sorted((cate1, cate2) -> {
                    return (cate1.getSort() == null ? 0 : cate1.getSort()) - (cate2.getSort() == null ? 0 : cate2.getSort());
                }).collect(Collectors.toList());
        return res;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //1.检查是否有关联其他分类
        baseMapper.deleteBatchIds(asList);
    }

    @Override
//    @Caching(
//            evict = {
//                    @CacheEvict(value = "category", key = "'getFirstCate'"),
//                    @CacheEvict(value = "category", key = "'getCatalogJson'")
//            }
//    )
    @CacheEvict(value = "category", allEntries = true)
    public void updateCascade(CategoryEntity category) {
        //修改category表
        this.updateById(category);
        //修改关联表
        if (StringUtils.isNotBlank(category.getName())) {

            categoryBrandRelationService.updateCascade(category.getCatId(), category.getName());
        }
    }

    @Cacheable(value = "category", key = "#root.methodName")
    @Override
    public List<CategoryEntity> getFirstCate() {
        List<CategoryEntity> entities = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return entities;
    }

    /**
     * 1.加上本地锁能锁住本地进程
     * 锁实例，因为spring容器默认为单例，所有请求都是访问的同一实例
     * 2.redisson客户端封装了redis的分布式锁的操作
     */
//    @Override
//    public Map<String, List<Catelog2Vo>> getCatalogJson() {
//        RLock lock = redissonClient.getLock("catalogjson-lock");
//        Map<String, List<Catelog2Vo>> data = null;
//        try {
//            lock.lock(30, TimeUnit.SECONDS);//阻塞式等待
//            data = getDataFromDb();
//        } finally {
//            lock.unlock();
//        }
//        return data;
//    }
    @Cacheable(value = "category", key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
//        RLock lock = redissonClient.getLock("catalogjson-lock");
//        Map<String, List<Catelog2Vo>> data = null;
//        try {
//            lock.lock(30, TimeUnit.SECONDS);//阻塞式等待
//            data = getDataFromDb();
//        } finally {
//            lock.unlock();
//        }
        Map<String, List<Catelog2Vo>> data = getDataFromDb();
        return data;
    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        System.out.println("缓存未命中");
        System.out.println("查询数据库");
        //将数据库的多次查询变为一次
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);

        //1、查出所有分类
        //1、1）查出所有一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        Map<String, List<Catelog2Vo>> parentCid = null;
        //封装数据
        parentCid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的一级分类,查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());

            //2、封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName().toString());

                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());

                    if (level3Catelog != null) {
                        List<Catelog2Vo.Category3Vo> category3Vos = level3Catelog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return category3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(category3Vos);
                    }

                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));

        return parentCid;
    }

//    private Map<String, List<Catelog2Vo>> getDataFromDb() {
//        Map<String, List<Catelog2Vo>> parentCid = null;
//        if (StringUtils.isBlank(redisTemplate.opsForValue().get("catalogjson"))) {
//            System.out.println("缓存未命中");
//            System.out.println("查询数据库");
//            //将数据库的多次查询变为一次
//            List<CategoryEntity> selectList = this.baseMapper.selectList(null);
//
//            //1、查出所有分类
//            //1、1）查出所有一级分类
//            List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
//
//            //封装数据
//            parentCid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
//                //1、每一个的一级分类,查到这个一级分类的二级分类
//                List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
//
//                //2、封装上面的结果
//                List<Catelog2Vo> catelog2Vos = null;
//                if (categoryEntities != null) {
//                    catelog2Vos = categoryEntities.stream().map(l2 -> {
//                        Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName().toString());
//
//                        //1、找当前二级分类的三级分类封装成vo
//                        List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
//
//                        if (level3Catelog != null) {
//                            List<Catelog2Vo.Category3Vo> category3Vos = level3Catelog.stream().map(l3 -> {
//                                //2、封装成指定格式
//                                Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
//
//                                return category3Vo;
//                            }).collect(Collectors.toList());
//                            catelog2Vo.setCatalog3List(category3Vos);
//                        }
//
//                        return catelog2Vo;
//                    }).collect(Collectors.toList());
//                }
//
//                return catelog2Vos;
//            }));
//            redisTemplate.opsForValue().set("catalogjson", JSON.toJSONString(parentCid));
//
//        }
//
//        String catalogjson = redisTemplate.opsForValue().get("catalogjson");
//        Map<String, List<Catelog2Vo>> map = JSON.parseObject(catalogjson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
//        });
//        return map;
//    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parentCid) {
        List<CategoryEntity> categoryEntities = selectList.stream().filter(item -> item.getParentCid().equals(parentCid)).collect(Collectors.toList());
        return categoryEntities;
        // return this.baseMapper.selectList(
        //         new QueryWrapper<CategoryEntity>().eq("parent_cid", parentCid));
    }

    private List<CategoryEntity> getChildrens(CategoryEntity category, List<CategoryEntity> all) {
        List<CategoryEntity> res = all.stream().filter(cate -> category.getCatId() == cate.getParentCid())
                .map(cate -> {
                    cate.setChildren(getChildrens(cate, all));
                    return cate;
                }).sorted((cate1, cate2) -> {
                    return (cate1.getSort() == null ? 0 : cate1.getSort()) - (cate2.getSort() == null ? 0 : cate2.getSort());
                }).collect(Collectors.toList());
        return res;
    }

}